var express = require('express');

//1 创建一个路由对象
var router = express.Router();
//2 挂载具体的路由

var users = [
	{'id':'1','userName':'张三','birthday':'2019-02-09','age':'23'},
	{'id':'2','userName':'李四','birthday':'1998-03-19','age':'33'}
];
//首页
router.get("/",function(req,res){
	res.render('index.html',{'users':users});
});
//新增页面
router.get("/addpage",function(req,res){
	res.render('add.html');
});
//新增保存
router.post("/user/save",function(req,res){
	req.body.id = Date.now();
	users.push(req.body);
	//保存成功后跳转到首页
	res.redirect("/");
});

//修改页面
router.get("/user/editpage",function(req,res){
	var id = req.query.id;
	var user;
	for(var i = 0;i<users.length;i++){
		if(users[i].id == id){
			user = users[i];
			break;
		}
	}
	res.render("./edit.html",{"user":user});
});
//修改保存
router.post("/user/edit",function(req,res){
	var id = req.body.id;
	for(var i = 0;i<users.length;i++){
		if(users[i].id == id){
			users.splice(i,1);
		}
	}
	users.push(req.body);
	//保存成功后跳转到首页
	res.redirect("/");
});

//删除
router.get("/delete",function(req,res){
	var id = req.query.id;
	console.log("id:"+id);
	for(var i = 0;i<users.length;i++){
		console.log(users[i].id +" "+id);
		if(users[i].id == id){
			console.log("删除");
			users.splice(i,1);
		}
	}
	//保存成功后跳转到首页
	res.redirect("/");
});
//3 导出路由对象
module.exports = router;